package com.xiu.util;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class Unzip {
	/**
	 * 解压文件到指定目录
	 */
	@SuppressWarnings("rawtypes")
	public static List<String> unZipFiles(String zipFileName, String descDir)
			throws IOException {
		File pathFile = new File(descDir);
		if (!pathFile.exists()) {
			pathFile.mkdirs();
		}
		// 解决zip文件中有中文目录或者中文文件
		ZipFile zip = new ZipFile(new File(zipFileName), Charset.forName("GBK"));
		List<String> fileNameList=new ArrayList<String>();
		
		for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {
			ZipEntry entry = (ZipEntry) entries.nextElement();
			String zipEntryName = entry.getName();
			InputStream in = zip.getInputStream(entry);
			String outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
			// 判断路径是否存在,不存在则创建文件路径
			File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
			if (!file.exists()) {
				file.mkdirs();
			}
			// 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
			if (new File(outPath).isDirectory()) {
				continue;
			}
			// 输出文件路径信息
			fileNameList.add(outPath);
			OutputStream out = new FileOutputStream(outPath);
			byte[] buf1 = new byte[1024];
			int len;
			while ((len = in.read(buf1)) > 0) {
				out.write(buf1, 0, len);
			}
			in.close();
			out.close();
		}
		return fileNameList;
	}

	public static void main(String[] args) throws IOException {
		/**
		 * 解压文件
		 */
		List<String> fileNameList=unZipFiles("d:/jars/pics啊啊.zip", "d:/jars");
		if(fileNameList.size()!=0){
			System.out.println(fileNameList);
		}
		System.out.println("d:/jars/pics啊啊.zip".substring(0, "d:/jars/pics啊啊.zip".lastIndexOf(".zip")));
		System.out.println(new File(fileNameList.get(0)).getName());
	}

}
